﻿using Consul;

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace Service.Framework.Register
{
    public class ConsulRegister : IConsulRegister
    {
        private readonly ConsulRegisterOptions _consulRegisterOptions;

        public ConsulRegister(IOptionsMonitor<ConsulRegisterOptions> consulRegisterOptions)
        {
            _consulRegisterOptions = consulRegisterOptions.CurrentValue;
        }

        public async Task ConsulRegistAsync()
        {
            var client = new ConsulClient(options =>
            {
                options.Address = new Uri(_consulRegisterOptions.Address); // Consul客户端地址
            });

            var registration = new AgentServiceRegistration
            {
                ID = Guid.NewGuid().ToString(), // 唯一Id
                Name = _consulRegisterOptions.Name, // 服务名(分组--多个实例组成的集群)
                Address = _consulRegisterOptions.Ip, // 服务绑定IP
                Port =_consulRegisterOptions.Port, // 服务绑定端口
                //Tag 标签
                Check = new AgentServiceCheck
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 服务启动多久后注册
                    Interval = TimeSpan.FromSeconds(10), // 健康检查时间间隔
                    HTTP = $"{_consulRegisterOptions.Scheme}://{_consulRegisterOptions.Ip}:{_consulRegisterOptions.Port}{_consulRegisterOptions.HealthCheck}", // 健康检查地址
                    Timeout = TimeSpan.FromSeconds(5) // 超时时间
                }
            };
            await client.Agent.ServiceDeregister(registration.ID);
            await client.Agent.ServiceRegister(registration);
        }


        void RegisterConsul(IHostApplicationLifetime appLifetime)
        {
            string currentIp = "172.17.64.1";
            using var client = new ConsulClient(x => x.Address = new Uri("http://127.0.0.1:8500"));
            var check = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务停止后，5s开始接触注册
                HTTP = $"http://{currentIp}:5165/healthcheck",//健康检查
                Interval = TimeSpan.FromSeconds(10),//每10s轮询一次健康检查
                Timeout = TimeSpan.FromSeconds(5),
            };
            var service = new AgentServiceRegistration()
            {
                Checks = new[] { check },
                ID = Guid.NewGuid().ToString(),
                Name = "OrderService",
                Port = 5165,//60002,
                Address = currentIp//"192.168.88.1"
            };
            client.Agent.ServiceRegister(service).Wait();
            appLifetime.ApplicationStopped.Register(() =>
            {
                using var consulClient = new ConsulClient(x => x.Address = new Uri("http://127.0.0.1:8500"));
                consulClient.Agent.ServiceDeregister(service.ID).Wait();
            });
        }

    }
}
